package com.service.component.group.services.impl;

/**
 * @author ：Calvin
 * @create ：2021/7/23 9:03
 * @description：组服务实现
 * @modified By：
 * @version: 1.0.0$
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.service.component.common.CommonResult;
import com.service.component.common.utils.CommonUtils;
import com.service.component.group.entity.Group;
import com.service.component.group.mapper.GroupMapper;
import com.service.component.group.services.GroupServices;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class GroupServiceImpl implements GroupServices {

    @Autowired
    private GroupMapper groupMapper;

    @Override
    public CommonResult insertGroup(Group groupParam) {
        Group group = groupMapper.selectOne(new QueryWrapper<Group>().eq("GROUP_NAME_EN", groupParam.getGroupNameEn()));
        if(ObjectUtils.isNotEmpty(group)){
          return CommonResult.commonResult(CommonResult.ResultCode.DATA_EXIST);
        }
        groupParam.setGroupNo(getRandomUserNo());
        return CommonResult.success(groupMapper.insert(groupParam));
    }

    /**
     * 生成随机的用户编号并且在数据库中不存在
     * @return
     */
    public String getRandomUserNo() {
        //随机生成7为编号
        String randomNo = CommonUtils.getRandomNo(7);
        //根据生成的编号，查询数据库，如果存在就重新生成并查库，知道不存在为止
        Group group = groupMapper.selectOne(new QueryWrapper<Group>().eq("GROUP_NO", randomNo));
        if (ObjectUtils.isNotEmpty(group)) {
            return getRandomUserNo();
        }
        return randomNo;
    }
}
